package org.xcorpio.java8.chapter05;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BuildingStreams {
    private static Logger logger = LoggerFactory.getLogger(BuildingStreams.class);

    public static void main(String[] args) {
        // stream from values
        Stream<String> fromValues = Stream.of("Java8", "Lambdas", "In", "Action");
        fromValues.map(String::toUpperCase).forEach(System.out::println);
        // stream from array
        int[] nums = { 4, 5, 6, 8, 9 };
        Arrays.stream(nums).sorted().forEach(System.out::println);
        // stream from file
        try (Stream<String> lines = Files.lines(Paths.get("pom.xml"), Charset.defaultCharset())) {
            lines.forEach(System.out::println);
        } catch (Exception e) {
            logger.warn(ExceptionUtils.getMessage(e));
        }
        // creating infinite streams
        Stream.iterate(0, n -> n + 2)
              .limit(10)
              .forEach(System.out::println);
        Stream.iterate(new int[] {0, 1}, t -> new int[] {t[1], t[0] + t[1]})
              .limit(10)
              .forEach(t -> System.out.println("(" + t[0] + "," + t[1] + ")"));
        Stream.generate(Math::random)
              .limit(5)
              .forEach(System.out::println);
        IntSupplier fib = new IntSupplier() {
            private int previous = 0;
            private int current = 1;
            @Override
            public int getAsInt() {
                int oldPrevious = this.previous;
                this.previous = this.current;
                this.current = oldPrevious + this.current;
                return oldPrevious;
            }
        };
        IntStream.generate(fib).limit(5).forEach(System.out::println);
    }
}
